package com.java.system.controller;

import com.alibaba.fastjson.JSON;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;
import com.java.common.utils.UuidUtil;
import com.java.system.entity.User;
import com.java.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 列表查询
     */
    @PostMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @PostMapping("/save")
    public R updateOrSave(@RequestBody User user) {
        userService.updateOrSave(user);
        return R.ok(user);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable String id) {
        userService.removeById(id);
        return R.ok();
    }

    /**
     * 重置密码
     */
    @PostMapping("/save-password")
    public R restPassword(@RequestBody User user) {
        userService.restPassword(user);
        return R.ok();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpServletRequest request) {
        log.info("用户登录开始");
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        // 根据验证码token去获取缓存中的验证码，和用户输入的验证码是否一致
        String imageCode = redisTemplate.opsForValue().get(user.getImageCodeToken());
        log.info("从redis中获取到的验证码：{}", imageCode);
        if (StringUtils.isEmpty(imageCode)) {
            log.info("用户登录失败，验证码已过期");
            return R.error("验证码已过期");
        }
        if (!imageCode.toLowerCase().equals(user.getImageCode().toLowerCase())) {
            log.info("用户登录失败，验证码不对");
            return R.error("验证码不对");
        } else {
            // 验证通过后，移除验证码
            redisTemplate.delete(user.getImageCodeToken());
        }

        User loginUser = userService.login(user);
        String token = UuidUtil.getShortUuid();
        loginUser.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUser), 3600, TimeUnit.SECONDS);
        return R.ok(loginUser);
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout/{token}")
    public R logout(@PathVariable String token) {
        redisTemplate.delete(token);
        log.info("从redis中删除token:{}", token);
        return R.ok();
    }
}
